package org.example.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * 分区器
 * @ClassName PartitionProducer
 * @Author 小坏
 * @Date 2021/10/31、15:48
 * @Version 1.0
 */
public class PartitionProducer {
    public static void main(String[] args) {
        Properties properties = new Properties();

        //指定连接的kafka集群
        //指定连接的kafka集群
        properties.put("bootstrap.servers", "hadoop102:9092");

        //Ack应答级别
        properties.put("acks", "all");

        //重试次数
        properties.put("retries", 3);

        //批次大小
        properties.put("batch.size", 16384);

        //等待时间
        properties.put("linger.ms", 1);

        properties.put("buffer.memory", 33554432);
        //RecordAccumulator 缓 冲区大小
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        //添加分区器
        properties.put("partitioner.class","org.example.partitioner.MyPartitioner");

        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        for (int i = 0; i < 10; i++) {
            producer.send(new ProducerRecord<>("aaa", "atguigu-" + i),
                    (recordMetadata, e) -> {
                        if (e == null) {
                            System.out.println(recordMetadata.partition() + "--" + recordMetadata.offset());
                        } else {
                            e.getMessage();
                        }
                    });
        }

        producer.close();
    }
    }
